package logic

import (
	"context"

	"mall/common/enumx"
	"mall/common/resultx"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/types/blog"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchKeywordListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchKeywordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchKeywordListLogic {
	return &SearchKeywordListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchKeywordListLogic) SearchKeywordList(in *blog.SearchKeywordListReq) (*blog.SearchKeywordListResp, error) {
	logx.Infof("SearchKeywordListReq: %+v ", in)
	// Limit:10 Preload:\"blogBook:Id,Title,Slug;blogMedia:Uid,Id,Url,Thumbnail,Order;blogBookRelation:brand\" EagerLoad:\"blogBook:blogMedia,blogBookRelation\" Filter:\"logSlug,equalTo:perfumes;logType,equalTo:141\" VisitorId:10002 PlatformId:1

	if in.PlatformId == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	filterMap := make(map[string]map[string][]interface{})
	filterMap[model.BlogUserSearchLogColumns.PlatformID] = map[string][]interface{}{
		"equalTo": []interface{}{in.PlatformId},
	}
	filterMap[model.BlogUserSearchLogColumns.Status] = map[string][]interface{}{
		"equalTo": []interface{}{enumx.ObjectStatusAproved},
	}
	searchLogList, count, err := l.svcCtx.BlogUser.GetSearchLogs(l.ctx, model.M{
		"offset": in.Offset,
		"limit":  in.Limit,
	}, 2, filterMap)
	if err != nil {
		return nil, err
	}

	var logs []*blog.BlogMeta
	if len(searchLogList) > 0 {
		for _, log := range searchLogList {
			logs = append(logs, &blog.BlogMeta{
				Id:  int64(log.SearchLogID),
				Key: log.Keyword,
			})
		}
	}

	var hasNextPage int32
	var hasPreviousPage int32
	if count > 1 {
		hasNextPage = 1
		count = count - 2
	}
	if count > 0 {
		hasPreviousPage = 1
	}

	return &blog.SearchKeywordListResp{
		Data: logs,
		HasNextPage: hasNextPage,
		HasPreviousPage: hasPreviousPage,
	}, nil
}
